package net.neiquan.applibrary.wight;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import net.neiquan.applibrary.R;

import org.haitao.common.utils.AppLog;

/**
 * 带进度条的WebView
 */

public class ProgressWebView extends WebView {
	private Activity activity;
	/**
	 * 视频全屏参数
	 */
	protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
	private View customView;
	private FrameLayout fullscreenContainer;
	private WebChromeClient.CustomViewCallback customViewCallback;
	private ProgressBar progressbar;

	public ProgressWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
		progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 5, 0, 0));

		Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
		progressbar.setProgressDrawable(drawable);
		addView(progressbar);
		setWebViewClient(new MyWebViewClient());
		setWebChromeClient(new WebChromeClient());
		// 是否可以缩放
//		getSettings().setSupportZoom(true);
//		getSettings().setBuiltInZoomControls(true);
		initWebViewSetting();
	}

	public void setActivity(Activity activity) {
		this.activity = activity;
	}

	public class MyWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 错误链接访问错误的全局化链接
			AppLog.e(errorCode + "========222=========" + description + "========222=======" + failingUrl);
//            view.loadUrl("file:///android_asset/404.html");
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			super.onReceivedSslError(view, handler, error);
			//handler.cancel(); // Android默认的处理方式
			//handleMessage(Message msg); // 进行其他处理
			handler.proceed();  // 接受所有网站的证书
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}

	}

	public class WebChromeClient extends android.webkit.WebChromeClient {

		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			AppLog.e("==========onConsoleMessage========" + consoleMessage.message());
			return super.onConsoleMessage(consoleMessage);
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress == 100) {
				progressbar.setVisibility(GONE);
			} else {
				if (progressbar.getVisibility() == GONE)
					progressbar.setVisibility(VISIBLE);
				progressbar.setProgress(newProgress);
			}
			super.onProgressChanged(view, newProgress);
		}

		/*** 视频播放相关的方法 **/

		@Override
		public View getVideoLoadingProgressView() {
			FrameLayout frameLayout = new FrameLayout(activity);
			frameLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            frameLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			return frameLayout;
		}

		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			showCustomView(view, callback);
		}

		@Override
		public void onHideCustomView() {
			hideCustomView();
		}
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
		lp.x = l;
		lp.y = t;
		progressbar.setLayoutParams(lp);
		super.onScrollChanged(l, t, oldl, oldt);
	}

//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
//        super.onMeasure(widthMeasureSpec, expandSpec);
//    }

	/**
	 * 初始化 WebViewSetting
	 * 各种属性
	 */
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebViewSetting() {
		WebSettings mSettings = getSettings();
		// 支持获取手势焦点
		requestFocusFromTouch();
		setHorizontalFadingEdgeEnabled(true);
		setVerticalFadingEdgeEnabled(false);
		setVerticalScrollBarEnabled(false);
		// 支持JS
		mSettings.setJavaScriptEnabled(true);
		mSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		mSettings.setBuiltInZoomControls(true);
		mSettings.setDisplayZoomControls(true);
		mSettings.setLoadWithOverviewMode(true);
		// 支持插件
		mSettings.setPluginState(WebSettings.PluginState.ON);
		mSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
		// 自适应屏幕
		mSettings.setUseWideViewPort(true);
		mSettings.setLoadWithOverviewMode(true);
		// 支持缩放
		mSettings.setSupportZoom(false);//就是这个属性把我搞惨了，
		// 隐藏原声缩放控件
		mSettings.setDisplayZoomControls(false);
		// 支持内容重新布局
		mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		mSettings.supportMultipleWindows();
		mSettings.setSupportMultipleWindows(true);
		// 设置缓存模式
		mSettings.setDomStorageEnabled(true);
		mSettings.setDatabaseEnabled(true);
		mSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		mSettings.setAppCacheEnabled(true);
		mSettings.setAppCachePath(getContext().getCacheDir().getAbsolutePath());
		// 设置可访问文件
		mSettings.setAllowFileAccess(true);
		mSettings.setNeedInitialFocus(true);
		// 支持自定加载图片
		if (Build.VERSION.SDK_INT >= 19) {
			mSettings.setLoadsImagesAutomatically(true);
		} else {
			mSettings.setLoadsImagesAutomatically(false);
		}
		mSettings.setNeedInitialFocus(true);
		// 设定编码格式
		mSettings.setDefaultTextEncodingName("UTF-8");
	}

	/**
	 * 视频播放全屏
	 **/
	private void showCustomView(View view, android.webkit.WebChromeClient.CustomViewCallback callback) {
		// if a view already exists then immediately terminate the new one
		if (customView != null) {
			callback.onCustomViewHidden();
			return;
		}
		activity.getWindow().getDecorView();
		FrameLayout decor = (FrameLayout) activity.getWindow().getDecorView();
		fullscreenContainer = new FullscreenHolder(activity);
		fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
		decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
		customView = view;
		setStatusBarVisibility(false);
		customViewCallback = callback;
	}

	/**
	 * 隐藏视频全屏
	 */
	private void hideCustomView() {
		if (customView == null) {
			return;
		}
		setStatusBarVisibility(true);
		FrameLayout decor = (FrameLayout) activity.getWindow().getDecorView();
		decor.removeView(fullscreenContainer);
		fullscreenContainer = null;
		customView = null;
		customViewCallback.onCustomViewHidden();
		setVisibility(View.VISIBLE);
	}

	/**
	 * 全屏容器界面
	 */
	static class FullscreenHolder extends FrameLayout {

		public FullscreenHolder(Context ctx) {
			super(ctx);
			setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
		}

		@Override
		public boolean onTouchEvent(MotionEvent evt) {
			return true;
		}
	}

	private void setStatusBarVisibility(boolean visible) {
		int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
		activity.getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

//    应该是activity的onKeyUp方法
//    @Override
//    public boolean onKeyUp(int keyCode, KeyEvent event) {
//        switch (keyCode) {
//            case KeyEvent.KEYCODE_BACK:
//                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
//                if (customView != null) {
//                    hideCustomView();
//                } else if (canGoBack()) {
//                    goBack();
//                } else {
//                    activity.finish();
//                }
//                return true;
//            default:
//                return super.onKeyUp(keyCode, event);
//        }
//    }
}
